package com.lijz.one.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lijz.annotation.AuthIgnore;
import com.lijz.annotation.UserAccess;
import com.lijz.constants.Constants;
import com.lijz.one.user.entity.User;
import com.lijz.one.user.service.IUserService;
import com.lijz.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lijz
 * @since 2018-10-24
 */
@RestController
@RequestMapping("/user")
public class UserController {

	@Autowired
	private IUserService userService;

	@Autowired
	private RedisUtil redisUtil;


	@UserAccess
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String saveUser(@RequestBody User user) {
		boolean save = userService.save(user);
		System.out.println("user:" + user.getUserName());
		return user.getId() + "";
	}

	@UserAccess
	@AuthIgnore
	@RequestMapping("/login")
	public String login(@RequestBody User user) {
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		//没加判空处理
		queryWrapper.setEntity(user);
//		queryWrapper.allEq(params, true);
		user = userService.getOne(queryWrapper);
		if (user == null) {
			return "user not exit";
		} else {
			user.setLoginStartTime(LocalDateTime.now());
			userService.updateById(user);
			String tokenId = UUID.randomUUID().toString();
			String token = Constants.TOKEN_ + tokenId;
			Map<String, Object> map = new HashMap<>();
			map.put("userid", user.getId());
			map.put("mobile", user.getMobile());
			map.put("islogin", true);
			map.put("creattime", LocalDateTime.now());
			redisUtil.hmset(token, map);
			redisUtil.expire(token, 24 * 60 * 60);
			redisUtil.lSet(Constants.TOKENS, token);
			redisUtil.hset("userid_" + user.getId(), Constants.TOKEN, token);
			return "success!" + "token = " + tokenId;
		}
	}

	@RequestMapping("/test")
	@UserAccess
	@AuthIgnore
	public void testApi() {
		System.out.println("user:" + userService.list(null));
	}
}
